package com.kymatrix.kycarbon.xsmd.common.exception;

import com.kymatrix.kycarbon.xsmd.common.business.common.ResultResp;
import com.kymatrix.kycarbon.xsmd.common.constants.Constant;
import com.kymatrix.kycarbon.xsmd.common.util.Exceptions;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 统一处理异常
     */
    @ExceptionHandler({Exception.class})
    public ResultResp<String> handleException(Exception e) {
        log.error("请求出现异常", e);
        String defaultFaliMessage = Constant.FAILED;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            String key = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            return ResultResp.error(key, null);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException exception = (HttpRequestMethodNotSupportedException) e;
            return ResultResp.error(exception.getMethod() + " not support ", null);
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            List<String> resList = new ArrayList<>();
            for (ObjectError allError : bindException.getAllErrors()) {
                resList.add(allError.getDefaultMessage());
            }
            return ResultResp.error(
                    resList.isEmpty() ? defaultFaliMessage : resList.stream().collect(Collectors.joining(";")));
        } else if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            return ResultResp.error(businessException.getMessage(), null);
        } else if (e instanceof MissingRequestHeaderException) {
            MissingRequestHeaderException exception = (MissingRequestHeaderException) e;
            return ResultResp.error(exception.getHeaderName() + "不能为空");
        } else {
            return ResultResp.error(Constant.FAILED, Exceptions.getStackTraceAsString(e));
        }
    }
}
